﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wx_api.Data;
using ExcelConfig;
using Dapper;
using wx_api.data.Model;
using wx_api.data.Dto;
using System.Net.Sockets;

namespace wx_api.data.Database
{
    public class Wx_apiDB : IDisposable
    {
        internal IRepo repo;
        public Wx_apiDB()
        {
            var connectstring = AppConfig.Text("wx-api-db");
            repo = new MysqlRepo(connectstring);
        }
        /// <summary>
        /// 更新wx app
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        public int UpdateWxApp(string tag, string appid, string secret)
        {
            repo.Open();
            var oks = 0;
            var wxapp = new WxApp();
            wxapp.Id = Guid.NewGuid();
            wxapp.Tag = tag;
            wxapp.AppId = appid;
            wxapp.Secret = secret;
            wxapp.CreateTime = DateTime.UtcNow;
            wxapp.UpdateTime = DateTime.UtcNow;
            var id_last = repo.Connection.QueryFirstOrDefault<Guid>("select Id from wx_app where AppId=@AppId", wxapp);
            var update_mode = false;
            if (id_last != Guid.Empty)
            {
                wxapp.Id = id_last;
                update_mode = true;
            }

            using (var transaction = repo.Connection.BeginTransaction())
            {
                try
                {
                    if (update_mode)
                    {
                        oks = repo.Connection.Execute("update wx_app set Tag=@Tag, Secret=@Secret, UpdateTime=@UpdateTime where Id=@Id;", wxapp, transaction);
                    }
                    else
                    {
                        oks = repo.Connection.Execute("insert into wx_app (Id, Tag, AppId, Secret, CreateTime, UpdateTime) values (@Id, @Tag, @AppId, @Secret, @CreateTime, @UpdateTime);", wxapp, transaction);
                    }
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    transaction.Rollback();
                    // 处理异常
                    Console.WriteLine(ex.Message);
                }
            }
            return oks;
        }
        public WxAppInfo ReadAppSecret(string tag)
        {
            var info = repo.Connection.QueryFirstOrDefault<WxAppInfo>("select AppId, Secret from wx_app where Tag=@Tag;", new { Tag = tag });
            if(info != null) return info;
            return new WxAppInfo();
        }
        public void UpdateWxToken(string appid, string token, DateTime expire)
        {
            repo.Open();

            var wxToken = new WxToken();
            wxToken.Id = Guid.NewGuid();
            wxToken.AppId = appid;
            wxToken.RefreshTime = DateTime.UtcNow;
            wxToken.ExpireTime = expire;
            wxToken.AccessToken = token;
            var id_last = repo.Connection.QueryFirstOrDefault<Guid>("select Id from wx_token where AppId=@AppId", wxToken);
            var update_mode = false;
            if (id_last != Guid.Empty)
            {
                wxToken.Id = id_last;
                update_mode = true;
            }

            using (var transaction = repo.Connection.BeginTransaction())
            {
                try
                {
                    if (update_mode)
                    {
                        repo.Connection.Execute("update wx_token set AccessToken=@AccessToken, RefreshTime=@RefreshTime, ExpireTime=@ExpireTime where Id = @Id;", wxToken, transaction);
                    }
                    else
                    {
                        repo.Connection.Execute("insert into wx_token (Id, AppId, AccessToken, RefreshTime, ExpireTime) values (@Id, @AppId, @AccessToken, @RefreshTime, @ExpireTime);", wxToken, transaction);
                    }
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    transaction.Rollback();
                    // 处理异常
                    Console.WriteLine(ex.Message);
                }
            }
        }
        public WxTokenInfo ReadToken(string appid)
        {
            var info = repo.Connection.QueryFirstOrDefault<WxTokenInfo>("select AppId, AccessToken, ExpireTime from wx_token where AppId=@AppId;", new { AppId = appid });
            if (info != null) return info;
            return new WxTokenInfo();
        }
        public void UpdateWxTicket(string appid, string ticket, DateTime expire)
        {
            repo.Open();

            var wxTicket = new WxTicket();
            wxTicket.Id = Guid.NewGuid();
            wxTicket.AppId = appid;
            wxTicket.RefreshTime = DateTime.UtcNow;
            wxTicket.ExpireTime = expire;
            wxTicket.Ticket = ticket;
            var id_last = repo.Connection.QueryFirstOrDefault<Guid>("select Id from wx_ticket where AppId=@AppId", wxTicket);
            var update_mode = false;
            if (id_last != Guid.Empty)
            {
                wxTicket.Id = id_last;
                update_mode = true;
            }

            using (var transaction = repo.Connection.BeginTransaction())
            {
                try
                {
                    if (update_mode)
                    {
                        repo.Connection.Execute("update wx_ticket set Ticket=@Ticket, RefreshTime=@RefreshTime, ExpireTime=@ExpireTime where Id = @Id;", wxTicket, transaction);
                    }
                    else
                    {
                        repo.Connection.Execute("insert into wx_ticket (Id, AppId, Ticket, RefreshTime, ExpireTime) values (@Id, @AppId, @Ticket, @RefreshTime, @ExpireTime);", wxTicket, transaction);
                    }
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    transaction.Rollback();
                    // 处理异常
                    Console.WriteLine(ex.Message);
                }
            }
        }
        public WxTicketInfo ReadTicket(string appid)
        {
            var info = repo.Connection.QueryFirstOrDefault<WxTicketInfo>("select AppId, Ticket, ExpireTime from wx_ticket where AppId=@AppId;", new { AppId = appid });
            if (info != null) return info;
            return new WxTicketInfo();
        }
        public void Dispose()
        {
            repo.Dispose();
        }


    }
}
